package com.jiyinit.web.core.common.listener;

import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.common.util.GlobalsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 生成静态资源版本号
 * 版本号说明：
 * 1.版本号组成部分  包含两部分  A：可配置的变量X
 * 2.X在未上生产环境前，每次发布项目，会重新赋值（统一配置），当上了生成环境，此值不在做修改
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/12 11:41
 * @since 1.0
 */
public class ConfigInitializerListener implements ServletContextListener {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigInitializerListener.class);

    /**
     * ServletContext的上下文
     */
    private ServletContext servletContext;

    /**
     * js默认版本号
     */
    public final static String JS_DEFAULT_VERSION = "v_1.0";

    /**
     * Notification that the web application initialization
     * process is starting.
     * All ServletContextListeners are notified of context
     * initialization before any filter or servlet in the web
     * application is initialized.
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        this.setServletContext(servletContextEvent.getServletContext());
        //初始化版本号
        if(getServletContext() != null){
            initResourceVersion();
        }

    }

    /**
     * Notification that the servlet context is about to be shut down.
     * All servlets and filters have been destroy()ed before any
     * ServletContextListeners are notified of context
     * destruction.
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    private void initResourceVersion(){
        String version = "?v=123";
        /*String configVersion = GlobalsUtils.getValue("JS_VERSION_X");
        if(Check.isNullStr(configVersion)){
            configVersion = JS_DEFAULT_VERSION;
        }
        version += configVersion;*/
        getServletContext().setAttribute("VERSION", version);
    }

    public ServletContext getServletContext() {
        return servletContext;
    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
